package com.joelaws.prototype.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.json.JSONObject;

import com.joelaws.prototype.server.dao.DAOFactory;

public class UploadPicture extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		System.out.println("In upload picture!!!!");

		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		System.out.println("is multipart? " + isMultipart);

		long userID = Long.MIN_VALUE;
		JSONObject response = null;

		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(req);
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				if (item.isFormField()) {
					userID = Long.parseLong(Streams.asString(item.openStream()));
					System.out.println("Form field " + name + " with value " + userID + "detected.");
				} else {
					System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
					InputStream stream = item.openStream();
					byte[] myarray = new byte[500];
					int i = 0;
					while ((i = stream.read(myarray)) != -1) {
						byteStream.write(myarray, 0, i);
					}
					byteStream.flush();
					stream.close();

				}
			}
			String loc;

			// loc = "src/com/joelaws/prototype/public/images/people/" + userID + ".jpg";
			// System.out.println("Storing image to: " + loc);
			// writeFile(byteStream, loc);
			//
			// loc = "build/classes/com/joelaws/prototype/public/images/people/" + userID + ".jpg";
			// System.out.println("Storing image to: " + loc);
			// writeFile(byteStream, loc);

			loc = "/var/lib/tomcat-6/webapps/JPEntertainment/images/people/" + userID + ".png";
			System.out.println("Storing image to: " + loc);
			System.out.println("CanonicalPath " + new File("").getCanonicalPath());
			writeFile(byteStream, loc);

			DAOFactory.getUserDAO().getUser(userID).getNetworkingService().getPicture().setLocation(
					"images/people/" + userID + ".png");

			response = new JSONObject();
			response.put("success", true);
			response.put("error", "uploaded successfully");
			response.put("code", "232");
		} catch (Exception ex) {
			ex.printStackTrace();
			try {
				response = new JSONObject();
				response.put("success", false);
				response.put("error", "uploaded failed");
				response.put("code", "232");
			} catch (Exception e) {

			}
		}

		if (response != null) {
			Writer w = new OutputStreamWriter(resp.getOutputStream());
			w.write(response.toString());
			w.close();
			System.out.println("Image upload response: " + response.toString());
		}
		resp.setStatus(HttpServletResponse.SC_OK);
	}

	private void writeFile(ByteArrayOutputStream byteStream, String loc) throws IOException {

		File uploadedFile = new File(loc);
		FileOutputStream fos = new FileOutputStream(uploadedFile);
		fos.write(byteStream.toByteArray());
		fos.flush();
		fos.close();
	}
}
